/**
* @author Karthikeyan VJ
**/
// frame rate for the canvas
const FPS = 30;

// reference of the canvas
var stage = null;
// referbece for the 2D context
var context2D = null;

// game objects
var chopper = new Image();
var cX = 100;
var cY = 100;
var dropSpeed = 3;

var foeList = [];

var currentState = 0; // 0 - title, 1 - game, 2 - game over, 3 - you win
var chopperState = 0;
var expCnt = 1;

var hideChopper = false;
var gameText;
var overText;

var youText;
var winText;

var score = 0;

var preloadList = [];
var soundPreloadList = [];

// images
const TITLE 			= "assets/title.jpg";
const CHOPPER 			= "assets/chopper.png";
const CHOPPER_TILT 		= "assets/chopper_tilt.png";
const ROCK_1			= "assets/rock_1.png";
const ROCK_2			= "assets/rock_2.png";
const ROCK_3			= "assets/rock_3.png";
const EXPLOSION			= "assets/exp/exp_";
const GAME				= "assets/game.png";
const OVER				= "assets/over.png";
const YOU				= "assets/you.png";
const WIN				= "assets/win.png";

// sound
const EXPLODE_SFX		= "assets/sfx/mp3/exp.mp3";
const CHOPPER_SFX		= "assets/sfx/mp3/chopper.mp3";
const LOOP_1_SFX		= "assets/sfx/mp3/loop1.mp3";
const LOOP_2_SFX		= "assets/sfx/mp3/loop2.mp3";

const EXPLODE_SFX_OGG		= "assets/sfx/ogg/exp.ogg";
const CHOPPER_SFX_OGG		= "assets/sfx/ogg/chopper.ogg";
const LOOP_1_SFX_OGG		= "assets/sfx/ogg/loop1.ogg";
const LOOP_2_SFX_OGG		= "assets/sfx/ogg/loop2.ogg";


var canPlayMp3 = false;
var canPlayOgg = false;

var explode;
var chopper_sound;
var bg_loop_1;
var bg_loop_2;

// invoked when the window is loaded
window.onload = init;

function init()
{
	$(document).ready(function(){
		
		preloadList.push(TITLE);
		preloadList.push(CHOPPER);
		preloadList.push(CHOPPER_TILT);
		preloadList.push(ROCK_1);
		preloadList.push(ROCK_2);
		preloadList.push(ROCK_3);
		preloadList.push(GAME);
		preloadList.push(OVER);
		
		var a = document.createElement('audio');
		canPlayMp3 = !!(a.canPlayType && a.canPlayType('audio/mpeg;').replace(/no/, ''));
		canPlayOgg = !!(a.canPlayType && a.canPlayType('audio/ogg; codecs="vorbis"').replace(/no/, ''));
		
		//alert("canPlayOgg = " +canPlayOgg);
		if(canPlayMp3) {
			soundPreloadList.push(EXPLODE_SFX);
			soundPreloadList.push(CHOPPER_SFX);
			soundPreloadList.push(LOOP_1_SFX);
			soundPreloadList.push(LOOP_2_SFX);
			
		} else if(canPlayOgg) {
			// ogg
			//soundPreloadList.push(EXPLODE_SFX_OGG);
			//soundPreloadList.push(CHOPPER_SFX_OGG);
			soundPreloadList.push(LOOP_1_SFX_OGG);
			soundPreloadList.push(LOOP_2_SFX_OGG);
		}
		
		var i;
		for(i = 1; i <= 25; i++){
			if(i < 10){
				preloadList.push(EXPLOSION + "0" + i + ".gif");
			} else {
				preloadList.push(EXPLOSION + i + ".gif");
			}
		}
		
		stage = document.getElementById("stage");
		context2D = stage.getContext("2d");
		
		//tage.width = 480;
		//stage.height = 320;
		
		set_textRenderContext(context2D);
		//resizeCanvas();
		hideAddressBar();
		//window.onorientationchange();
		preloadAssets();
		//start();
		
	});
}

/**
window.onorientationchange = function()
{
	//var canvas = document.getElementById('stage');
	if (window.orientation % 180 == 0) {
		// portrait orientation
		rx = 320;
		ry = 320;
		
	}
	else {
		// landscape orientation, or window.orientation not supported
		rx = 480;
		ry = 320;
	}

	// resize the canvas
	stage.width = rx;
	stage.height = ry;

	
}
*/

function preloadAssets()
{
	
	context2D.clearRect(0, 0, stage.width, stage.height);
	var img = new Image();
	var i;
	for(i = 0; i < preloadList.length; i++){
		img.src = preloadList[i];
		resizeCanvas();
		context2D.clearRect(0, 0, stage.width, stage.height);
		
		context2D.fillStyle = "#000000";
		context2D.fillRect(0, 0, stage.width, stage.height);
		
		context2D.strokeStyle = "#ffffff";
		//context2D.font="13px Arial bold";
		context2D.strokeText("Loading Graphics... " + (i+1) + " / " + preloadList.length, 6, 20);
		
	}
	
	var aud;
	for(i = 0; i < soundPreloadList.length; i++){
		aud = new Audio(soundPreloadList[i]);
		context2D.clearRect(0, 0, stage.width, stage.height);
		context2D.fillStyle = "#000000";
		context2D.fillRect(0, 0, stage.width, stage.height);
		
		context2D.strokeStyle = "#ffffff";
		//context2D.font="13px Arial bold";
		context2D.strokeText("Loading Sound... " + (i+1) + " / " + soundPreloadList.length, 6, 20);
	}
	
	
	window.onload = start();
	//start();
}

function start()
{
		if(canPlayMp3) {
			explode = new Audio(EXPLODE_SFX);
			chopper_sound = new Audio(CHOPPER_SFX);
			bg_loop_1 = new Audio(LOOP_1_SFX);
			bg_loop_2 = new Audio(LOOP_2_SFX);
		} else if(canPlayOgg) {
			//explode = new Audio(EXPLODE_SFX_OGG);
			//chopper_sound = new Audio(CHOPPER_SFX_OGG);
			bg_loop_1 = new Audio(LOOP_1_SFX_OGG);
			bg_loop_2 = new Audio(LOOP_2_SFX_OGG);
		}
	
		chopper.src = CHOPPER;
		currentState = 0;
		
		$('body').bind("touchmove", onTouchMoveHL);
		//$('body').bind("dblclick", onDoubleClickHL);
		$('body').doubletap(
			/** doubletap-dblclick callback */
			onDoubleClickHL,
			/** touch-click callback (touch) */
			function(event){
				
			},
			/** doubletap-dblclick delay (default is 500 ms) */
			400
		);

		
		$('#stage').bind("touchstart", onStageMouseDownHL);
		$('#stage').bind("touchend", onStageMouseUpHL);
		
		$('#stage').bind("mousedown", onStageMouseDownHL);
		$('#stage').bind("mouseup", onStageMouseUpHL);
		
		$('#stage').bind("click", onStageClickHL);
		
		/*stage.addEventListener("touchstart", onStageMouseDownHL, false);
		stage.addEventListener("touchend", onStageMouseUpHL, false);
		
		stage.addEventListener("mousedown", onStageMouseDownHL, false);
		stage.addEventListener("mouseup", onStageMouseUpHL, false);
		
		stage.addEventListener("click", onStageClickHL, false);
		*/
		
		
		drawFoe();
		
		gameText = new gameGfx();
		overText = new overGfx();
		
		youText = new youGfx();
		winText = new winGfx();
		
		setInterval(loop, 1000 / FPS);
		//loop();
}

function drawFoe()
{
	foeList = [];
	var block;
	block = new foe(512, 71, ROCK_2);
	foeList.push(block);
	
	var block2 = new foe(700, 210, ROCK_2);
	foeList.push(block2);
	
	var block3 = new foe(842, 4, ROCK_3);
	foeList.push(block3);
	
	var block4 = new foe(1024, 163, ROCK_1);
	foeList.push(block4);
	
	var block5 = new foe(1212, 121, ROCK_2);
	foeList.push(block5);
	
	var block6 = new foe(1448, 11, ROCK_2);
	foeList.push(block6);
	
	var block8 = new foe(1631, 260, ROCK_3);
	foeList.push(block8);
	
	var block9 = new foe(1846, 13, ROCK_1);
	foeList.push(block9);
	
	var block10 = new foe(2016, 63, ROCK_1);
	foeList.push(block10);
	
	var block11 = new foe(2166, 63, ROCK_1);
	foeList.push(block11);
	
	var block11 = new foe(2304, 28, ROCK_2);
	foeList.push(block11);
	
	var block11 = new foe(2425, 250, ROCK_2);
	foeList.push(block11);
}

function foe(x, y, gfx)
{
	this.img = new Image();
	this.img.src = gfx;
	this.tx = x;
	this.ty = y;
	//this.src = "assets/chopper.png";
}

function gameGfx()
{
	this.img = new Image();
	this.img.src = GAME;
	this.tx = -150;
	this.ty = 80;
}

function overGfx()
{
	this.img = new Image();
	this.img.src = OVER;
	this.tx = 490;
	this.ty = 155;
}

function youGfx()
{
	this.img = new Image();
	this.img.src = YOU;
	this.tx = -150;
	this.ty = 80;
}

function winGfx()
{
	this.img = new Image();
	this.img.src = WIN;
	this.tx = 490;
	this.ty = 155;
}

function loop()
{
	window.scrollTo(0,1); 
	resizeCanvas();
	// clear canvas
	context2D.clearRect(0, 0, stage.width, stage.height);
	//window.scrollTo(0, 0);
	
	switch(currentState) {
		
		case 0:
			// game title
			if(canPlayOgg || canPlayMp3) {
				bg_loop_1.pause();
				bg_loop_2.play();
			}
			var titleImage = new Image();
			titleImage.src = TITLE;
			context2D.drawImage(titleImage, 0, 0);			
			drawCredits();
		break;
		
		case 1:
		case 2:
		case 3:
			// game play
			// draw sky
			if(canPlayOgg || canPlayMp3) {
				bg_loop_1.play();
				bg_loop_1.volume = 0.3;
				bg_loop_2.pause();
			}
			var sky_gradient = context2D.createLinearGradient(0, 0, 0, 320);
			sky_gradient.addColorStop(0, "#128CDC");
			sky_gradient.addColorStop(1, "#ABD0F5");
			context2D.fillStyle = sky_gradient;
			context2D.fillRect(0, 0, stage.width, stage.height);
			
			
			for(var i = 0; i < foeList.length; i++){
				//document.write(foeList[i].img);
				if(foeList[i].tx <= 490 && foeList[i].tx >= -50) {
					context2D.drawImage(foeList[i].img, foeList[i].tx, foeList[i].ty);					
				}
				foeList[i].tx -= 2;
				// hit detection (crappy)
				if(foeList[i].tx - cX <= 95 && (foeList[i].ty - cY <= 30 && cY <= (foeList[i].ty + foeList[i].img.height)) && cX < foeList[i].tx + 30){
					chopperState = 2;
				}
				
				if(foeList[foeList.length - 1].tx < -50 && chopperState != 2){
				//if(foeList[0].tx < -50){
					chopperState = 3;
				}
			}
			
			drawScore();
			
			// draw chopper
			if(hideChopper == false) {
				context2D.drawImage(chopper, cX, cY);
			}
			
			if(expCnt == 1 && chopperState!= 3){
				score ++;
			}
			
			
			if(chopperState == 0){
				// on mouse up
				chopper.src = CHOPPER_TILT;
				cY += dropSpeed;
				//chopper_sound.play();
				if(cY >= 290) {
					// kill the chopper
					chopperState = 2;
					
				}
				
			} else if(chopperState == 1) {
				// on mouse down				
				chopper.src = CHOPPER;
				cY -= dropSpeed;
				//chopper_sound.play();
				if(cY < 5) {
					// kill the chopper
					chopperState = 2;
				}
				
			} else if(chopperState == 2) {
				// game over
				// chopper kill
				if(cY > 260) cY = 260;
				
				if(expCnt == 1){
					//play sound
					if(canPlayMp3) {
						//chopper_sound.pause();
						explode.play();
					}
				}
				
				if(expCnt <= 25) {
					if(expCnt < 10)
						chopper.src = EXPLOSION + "0" + expCnt +".gif";
					else
						chopper.src = EXPLOSION + expCnt +".gif";
					expCnt++;
				} else {
					// do not show the chopper
					hideChopper = true;
					context2D.drawImage(gameText.img, gameText.tx, gameText.ty);
					if(gameText.tx <= 130) {
						gameText.tx += 5;
					}
					
					context2D.drawImage(overText.img, overText.tx, overText.ty);
					if(overText.tx >= 130) {
						overText.tx -= 5;
						
					} else {
						currentState = 2;
					}
					
					
				}
				
			} else if(chopperState == 3){
				
				// draw you win
				context2D.drawImage(youText.img, youText.tx, youText.ty);
				if(youText.tx <= 130) {
					youText.tx += 5;
				}
				
				context2D.drawImage(winText.img, winText.tx, winText.ty);
				if(winText.tx >= 145) {
					winText.tx -= 5;
					
				} else {
					currentState = 2;
				}
			}
			
			
		break;
		
		/*case 2:
			// game over
			
			
		break;*/
		
		/*case 3:
			// you win
		break;*/
	}
	
}

function reset()
{
	drawFoe();
	
	gameText = new gameGfx();
	overText = new overGfx();
	
	youText = new youGfx();
	winText = new winGfx();
	
	chopperState = 1;
	chopper.src = CHOPPER;
	hideChopper = false;
	cX = 100;
	cY = 100;
	score = 0;
	expCnt = 1;
	
}

function drawScore()
{
	
	context2D.strokeStyle = "#000000"
	//context2D.lineWidth = 2;
	//context2D.font="13px Arial bold";
    context2D.strokeText("Score: " + score, 6, 10, 11, 150);
	
	/*context2D.fillStyle = "#ffffff";
    context2D.font="13px Arial bold";
    context2D.fillText("Score: " + score, 6, 20);*/
	
}

function drawCredits()
{
	context2D.strokeStyle = "#cccccc"
	//context2D.lineWidth = 2;
	//context2D.font="10px Arial bold";
    context2D.strokeText("Programmed by, Karthikeyan VJ", 6, 300, 9, 150);
	
	/*context2D.fillStyle = "#cccccc";
    context2D.font="10px Arial bold";
    context2D.fillText("Programmed by, Karthikeyan VJ", 6, 310);*/
}

function resizeCanvas()
{
	//stage.width = window.innerWidth;
	//stage.height = window.innerHeight;
}
function onStageClickHL(e)
{
	if(currentState == 1) return;
	
	switch(currentState){
		case 0:
			currentState = 1;
		break;
		
		case 2:
			reset();
			currentState = 0;
		break;
	}
	
	e.stopPropagation();
}
function onStageMouseDownHL(e)
{
	if(chopperState == 2) return;
	chopperState = 1;
	
	e.stopPropagation();
}

function onStageMouseUpHL(e)
{
	if(chopperState == 2) return;
	chopperState = 0;
	
	e.stopPropagation();
}

function onTouchMoveHL(e)
{
	e.preventDefault();
	e.stopPropagation();
}

function onDoubleClickHL(e)
{
	e.preventDefault();	
	e.stopPropagation();
}

function hideAddressBar()
{
	// attempt to hide the browser's address bar
	//alert("hide");
	
	//setTimeout(function() { window.scrollTo(0, 1) }, 10 );
}
